package com.baidu.process.chat.parser.sourceHandler.impl;

import com.alibaba.fastjson.JSONObject;
import com.baidu.process.chat.core.action.Actions;
import com.baidu.process.chat.core.web.bean.IMRequestServer;
import com.baidu.process.chat.core.web.bean.eval.EvalResult;
import com.baidu.process.chat.core.web.bean.eval.EvalVO;
import com.baidu.process.chat.core.web.service.IEvaluationService;
import com.baidu.process.chat.parser.bean.QueryJsonStr;
import com.baidu.process.chat.parser.sourceHandler.BaseSourceHandler;
import com.baidu.process.config.service.OptAnswerService;
import com.baidu.process.constant.EvalConstant;
import com.baidu.process.constant.OptEventEnum;
import com.baidu.process.imchat.entity.ImResult;
import com.baidu.process.imchat.service.ImChatService;
import com.baidu.process.ngd.bean.NGDResBody;
import com.baidu.process.record.bean.DialogueRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.baidu.process.constant.RedisKey.*;

/**
 * @Author:fangyuchao
 * @Description: 系统处理期
 * @Date: Create in 14:42 2022/11/8
 */
@Service
public class SystemHandler implements BaseSourceHandler {
    @Autowired
    private OptAnswerService optAnswerService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Value("#{'${ngd.filter.answerActions}'.split(',')}")
    private List<String> answerActions;
    @Autowired
    private IEvaluationService evalResultService;
    @Autowired
    private ImChatService imChatService;
    @Override
    public QueryJsonStr handleQuery(NGDResBody ngdResBody, IMRequestServer imRequestServer, DialogueRecord dialogueRecord) {
        //给im发送的信息列表
        List<String> imMsgList = new ArrayList<>();
        String channel = imRequestServer.getChannel();
        QueryJsonStr queryJsonStr = new QueryJsonStr();
        NGDResBody.NGDQueryData  queryData = ngdResBody.getData();
        String sessionId = queryData.getSessionId();
        //重置澄清次数
        redisTemplate.opsForValue().set(ClarfyKey+sessionId,"0",10, TimeUnit.MINUTES);
        Map<String,Object>  answer = queryData.getAnswer();
        String answerText = answer.get("answerText").toString();
        queryJsonStr.setAnswer(excptAtion(answerText));
        String action = actionExract(answerText);
        queryJsonStr.setBot(actionExract(answerText));
        queryJsonStr.setSessionId(queryData.getSessionId());
        queryJsonStr.setContext(queryData.getContext());
        queryJsonStr.setSource(queryData.getSource());
        switch (action){
            case "1":
                //action是1，挂机的情况下推送满意度链接
                List<Map<String,Object>> msgBody = new ArrayList<>();
                Map<String,Object> map = new HashMap<>();
                map.put("msgType","TIMTextElem");
                Map<String,String> textMap = new HashMap<>();
                //调用满意度接口获取满意度链接
                EvalVO evalVO = new EvalVO();
                evalVO.setChannel(channel);
                evalVO.setSessionId(sessionId);
                EvalResult evalResult = evalResultService.pushEval(evalVO);
                //通过渠道推送不同链接格式
                textMap.put("text",optAnswerService.getAnswerByEvent(OptEventEnum.closeText.name()));
                //渠道0推送
                if (EvalConstant.CHANNEL_WX.equals(channel)){
                    map.put("msgType","TIMTextElem");
                    String evalUrl = JSONObject.parseObject(evalResult.getJsonString()).get("url").toString();
                    //拼接上满意度
                    textMap.put("text","<a href='"+evalUrl+"'>客户满意度调研</a>");
                }else{
                    map.put("msgType","TIMCustomElem");
                    String evalJson = evalResult.getJsonString();
                    //推送满意度
                    textMap.put("desc",evalJson);
                }
                map.put("msgContent",textMap);
                msgBody.add(map);
                ImResult imResult = imChatService.imChat(imRequestServer,msgBody);
                imMsgList.add(JSONObject.toJSONString(msgBody));
                //发完满意度后再提交关闭
                List<Map<String,Object>> closeMsgBody = new ArrayList<>();
                Map<String,Object> closeMap = new HashMap<>();
                Map<String,String> closeTextMap = new HashMap<>();
                closeTextMap.put("text",excptAtion(answerText));
                closeMap.put("msgContent",closeTextMap);
                closeMap.put("msgType","TIMClose");
                closeMsgBody.add(closeMap);
                ImResult imCloseResult = imChatService.imChat(imRequestServer,closeMsgBody);
                imMsgList.add(JSONObject.toJSONString(closeMsgBody));
                redisTemplate.delete(ImSilentNumKey+sessionId);
                redisTemplate.delete(ImTimeKey+sessionId);
                break;
                //2的情况下转人工，删除缓存不再触发静默策略
            case "2":
                redisTemplate.delete(ImSilentNumKey+sessionId);
                redisTemplate.delete(ImTimeKey+sessionId);
                break;
            default:
        }

        dialogueRecord.setImchatData(JSONObject.toJSONString(imMsgList));
        return queryJsonStr;

    }
    /**
     * 去除话术内的@@指令
     * @param answerText
     * @return
     */
    private String excptAtion(String answerText){
        String resultAnwer = answerText;
        for (String action :answerActions){
            resultAnwer = resultAnwer.replace(action,"");
        }
        return  resultAnwer;
    }


    //提取话术内的指令,去除@@符号
    private String actionExract(String suggestAnswer){
        //默认正常回复
        String action = "0";
        for (String action_1 : answerActions){
            if (suggestAnswer.contains(action_1)){
                action=action_1.replace("@","");
                break;
            }
        }
        return action;
    }
}
